package PageRank;


import org.apache.commons.lang.StringUtils;

import java.util.Arrays;

public class Node {
    //本节点的pr值
    private double pr;
    //附近出链的名字
    private String[] nearbyNodename;
    //定义分割符
    private static final char separator = '\t';

    //无参构造
    public Node() {
    }

    //有参构造
    public Node(double pr, String[] nearbyNodename) {
        this.pr = pr;
        this.nearbyNodename = nearbyNodename;
    }

    //证明他有出链
    public boolean havingNode() {
        return (nearbyNodename != null && nearbyNodename.length > 0);
    }
    //重写toString

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        //将属性放入
        sb.append(pr);
        //如果有出链
        if (havingNode()) {
            //StringUtils的join'方法可以在数组的每一个元素中间插入第二个参数
            sb.append(separator).append(StringUtils.join(nearbyNodename, separator));
        }
        return sb.toString();
    }

    //第二次及更多次运行时
    public static Node getNode(String line) throws Exception {
        String[] str = StringUtils.split(line, separator);
        //如果数据长度小于1说明数据没有传来pr值，数据错误
        if (str.length < 1) {
            throw new Exception("数据错误");
        }
        Node node = new Node();
        //将pr值赋予node
        node.setPr(Double.parseDouble(str[0]));
        //将str中从1开始到str.length结束的位置的元素赋给Nodename，也就是此链的出链
        node.setNearbyNodename(Arrays.copyOfRange(str, 1, str.length));
        return node;
    }

    //第一次运行的时候，设置每一个页面的初始权重pr值都是1
    public static Node getNode(String string, String line) throws Exception {
        return getNode(string + separator + line);
    }

    public double getPr() {
        return pr;
    }

    public void setPr(double pr) {
        this.pr = pr;
    }

    public String[] getNearbyNodename() {
        return nearbyNodename;
    }

    public void setNearbyNodename(String[] nearbyNodename) {
        this.nearbyNodename = nearbyNodename;
    }

    public static char getSeparator() {
        return separator;
    }
}